#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Logical clock layer

import sys 
import comm_channels

class clock(object):
    def __init__(self, comm_channel):
        self.comm_channel = comm_channel
        
    def print_output(self, text):
        self.comm_channel.print_output(text)

    def close_channel(self, dest):
        self.comm_channel.close_channel(dest)

    def send_message(self, dest, msg):
        self.comm_channel.send_message(dest, msg)
        
    def recv_message(self):
        return self.comm_channel.recv_message()

    def network_size(self):
        return self.comm_channel.network_size()

    def get_pid(self):
        return self.comm_channel.get_pid()

    def get_hosts(self):
        return self.comm_channel.get_hosts()
    
    def channel_state(self, channel):
        return self.comm_channel.channel_state(channel)

    def increase_clock(self):
        pass

    def get_clock(self):
        return None

    def close(self):
        self.comm_channel.close()

class lamport_clock(clock):
    def __init__(self, comm_channel):
        clock.__init__(self, comm_channel)
        self.clock = 0

    def get_clock(self):
        return self.clock

    def increase_clock(self):
        self.clock = self.clock + 1

    def send_message(self, dest, msg):
        self.increase_clock()
        self.comm_channel.send_message(dest, (msg, self.clock))

    def recv_message(self):
        origin, content = self.comm_channel.recv_message()
        msg, m_clock = content
        self.clock = max(self.clock, m_clock)
        self.increase_clock()
        return (origin, msg)
